<!--
@description: 小蜜蜂管理
@author: zhangzhan
@time: 2024-09-15 16:06:02
-->
<template>

  <page-container title="小蜜蜂管理">
    <!-- 表单区域 -->
    <el-form inline>
      <el-form-item label="搜索:">
        <el-input style="width: 240px" placeholder="名称/手机号" v-model="parameter.key"/>
      </el-form-item>

      <el-form-item label="状态:">
        <el-select v-model="parameter.status" placeholder="状态" style="width: 240px">
          <el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="selectClick">查询</el-button>
        <el-button type="success" plain @click="add">新增</el-button>
        <el-popconfirm title="确定删除吗?"
                       confirm-button-text="确定"
                       cancel-button-text="取消"
                       @Confirm="delByIds">
          <template #reference>
            <el-button type="danger" plain>批量删除</el-button>
          </template>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <div style="text-align:right"></div>

    <!-- -----------------表格---------------- -->
    <el-table :data="filterTableData"
              border size="large"
              row-key="managerId"
              style="width: 100%"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" fixed/>
      <el-table-column label="昵称" prop="nickname" width="120"/>
      <el-table-column label="手机号" prop="phone" width="120" show-overflow-tooltip/>
      <el-table-column label="代理人" prop="managerName" width="120" show-overflow-tooltip/>
      <el-table-column label="状态" prop="status" width="120" show-overflow-tooltip>
        <template v-slot="scope">
          <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              class="mt-2"
              style="margin-left: 24px"
              inline-prompt
              :active-icon="Check"
              :inactive-icon="Close"
              @change="updateStatus($event,scope.row.beesId,scope.row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="sex" width="120" show-overflow-tooltip>
        <template #default="scope">
          <span v-if="scope.row.sex === '1'">男</span>
          <span v-else-if="scope.row.sex === '2'">女</span>
          <span v-else-if="scope.row.sex === '3'">未知</span>
        </template>
      </el-table-column>
      <el-table-column label="省份" prop="province" width="120" show-overflow-tooltip/>
      <el-table-column label="城市" prop="city" width="120" show-overflow-tooltip/>
      <el-table-column label="区/县" prop="county" width="120" show-overflow-tooltip/>
      <el-table-column label="备注" prop="remark" width="120" show-overflow-tooltip/>
      <el-table-column label="总成功注册商户数" prop="totalSupplier" width="160" show-overflow-tooltip/>
      <el-table-column label="总收益" prop="totalEarnings" width="120" show-overflow-tooltip/>
      <el-table-column label="备注" prop="remark" show-overflow-tooltip/>
      <el-table-column label="创建时间" prop="createTime" width="120" show-overflow-tooltip/>
      <el-table-column label="创建时间" prop="updateTime" width="120" show-overflow-tooltip/>

      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-popconfirm title="确定删除吗?"
                         confirm-button-text="确定"
                         cancel-button-text="取消"
                         @Confirm="del(scope.row)">
            <template #reference>
              <el-button circle plain type="danger" :icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>


    <el-pagination background layout="->,prev, pager, next"
                   :total="paginations.total"
                   @change="tableChange"/>


    <BeesForm v-model:model-value="modelValue"
              v-model:form="form"
              v-model:title="title"
              @search="onSearch()"></BeesForm>
  </page-container>

</template>
<script setup>

//查询参数
import {Check, Close, Delete, Edit} from "@element-plus/icons-vue";
import RoleSave from "@/components/sys/role/RoleSave.vue";
import PageContainer from "@/components/PageContainer.vue";
import {beesListPage, beesDeleteByIds, beesUpdateStatus} from "@/api/sys/bees.js";
import {usePagination, useRequest} from "vue-request";
import {ElMessage} from "element-plus";
import {ref, computed} from "vue";
import BeesForm from "@/components/sys/bees/BeesForm.vue";
import {serverManager} from '@/stores/modules/mabager.js'
import { regionData } from 'element-china-area-data'
const title = ref(false)
const modelValue = ref(false)



// form表单参数
const form = ref({
  beesId: undefined,
  nickname: '',
  phone: '',
  username: '',
  password: '',
  status: '',
  area: [],
  province: '',
  city: '',
  county: '',
  managerId: serverManager.value.managerId,
  remark: ''
})

// 表单重置
function reset() {
  // eslint-disable-next-line no-sequences
  (form.value = {
    beesId: undefined,
    nickname: '',
    phone: '',
    username: '',
    password: '',
    status: '0',
    area: [],
    province: '',
    city: '',
    county: '',
    managerId: serverManager.value.managerId,
    remark: ''
  })
}

//新增按钮
function add() {
  modelValue.value = true
  title.value = true

}

const parameter = ref({
  page: 1,//当前页码
  limit: 10,//每页记录数
  status: '2',//'状态  1：禁用   0：正常'  ''空为全部
  key: ''//检索关键字
})

//分页查询
const {data, total, run: search} = usePagination((d) => beesListPage(d), {
  defaultParams: [parameter.value],
  pagination: {
    currentKey: 'page',
    pageSizeKey: 'limit',
    totalKey: 'data.data.page.totalCount',
  }
})

//分页数据计算属性
const paginations = computed(() => {
  return {
    current: parameter.value?.page, //当前页
    pageSize: parameter.value?.limit, //页大小
    total: total.value,
  }
})

//分页事件
function tableChange(currentPage, pageSize) {
  parameter.value.page = currentPage ?? 1
  parameter.value.limit = pageSize ?? 10
  search(parameter.value)
}

//小蜜蜂数据计算属性
const filterTableData = computed(() => {
  return data.value?.data?.data?.page?.list || []
})

function onSearch() {
  search(parameter.value)
}

//查询点击
function selectClick() {
  search(parameter.value)
}


//修改状态
const {runAsync: updateStatusById} = useRequest((d) => beesUpdateStatus(d),
    {
      manual: true
    }
)

async function updateStatus(on, beesId, status) {
  if (on) {
    const data = {beesId:beesId, status:status}

    await updateStatusById(data).then((res) => {
      if (res?.data.code !== 0) {
        //修改失败
        filterTableData.value.status = !filterTableData.value.status
        ElMessage.error('修改失败，请重试！')
      } else {
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
      }
    })
  }
}


let arr = []
const {run: deleteById} = useRequest((d) => beesDeleteByIds(d),
    {
      manual: true
    }
)

async function del(row) {
  arr.push({
    managerId: row.managerId,
    beesId: row.beesId,
    status: row.status
  })

  await deleteById(arr)
  arr = []
  search(parameter.value)
}

//收集选中的id
function handleSelectionChange(val) {
  val.forEach(po => {
    arr.push({
      managerId: po.managerId,
      beesId: po.beesId,
      status: po.status
    })
  })
}


async function delByIds() {
  await deleteById(arr)
  arr = []
  search(parameter.value)
}


const options = [
  {
    value: '0',
    label: '启用',
  },
  {
    value: '1',
    label: '禁用',
  },
  {
    value: '2',
    label: '全部',
  }
]

</script>